// app/model/invitation_model.js
'use strict';

module.exports = app => {
  const { STRING, INTEGER, DATE, ENUM, TEXT } = app.Sequelize;

  const Invitation = app.model.define('invitation', {
    id: {
      type: INTEGER,
      primaryKey: true,
      autoIncrement: true
    },
    organizationId: {
      type: INTEGER,
      allowNull: false,
      field: 'organization_id',
      comment: '组织ID'
    },
    email: {
      type: STRING(100),
      allowNull: false,
      comment: '被邀请人邮箱'
    },
    role: {
      type: STRING(50),
      comment: '邀请角色'
    },
    token: {
      type: STRING(100),
      allowNull: false,
      unique: true,
      comment: '邀请令牌'
    },
    status: {
      type: ENUM('pending', 'accepted', 'expired'),
      defaultValue: 'pending',
      comment: '邀请状态'
    },
    expiresAt: {
      type: DATE,
      allowNull: false,
      field: 'expires_at',
      comment: '过期时间'
    },
    invitedBy: {
      type: INTEGER,
      allowNull: false,
      field: 'invited_by',
      comment: '邀请人ID'
    },
    createdAt: {
      type: DATE,
      field: 'created_at'
    },
    updatedAt: {
      type: DATE,
      field: 'updated_at'
    }
  }, {
    tableName: 'invitations',
    timestamps: true,
    underscored: true
  });

  // 关联关系
  Invitation.associate = function() {
    app.model.InvitationModel.belongsTo(app.model.OrganizationModel, {
      foreignKey: 'organizationId',
      as: 'organization'
    });
    
    app.model.InvitationModel.belongsTo(app.model.UserModel, {
      foreignKey: 'invitedBy',
      as: 'inviter'
    });
  };

  return Invitation;
};